package com.db.stockexchange.client;

import java.io.IOException;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;

import com.db.stockexchange.client.ui.MainView;

/**
 * 
 * @author Rayman
 * It's not quite proper presenter from MVP model
 */
public class ClientPresenter {
	ClientEngine engine;
	MainView view;
	
	public ClientPresenter(MainView view) {
		this.view = view;
	}
	
	public boolean login(InetAddress address, int port, String clientID) {
		try {
			engine = new ClientEngine(clientID, address, port, this);
		} catch (IOException e) {
			return false;
		}
		
		return true;
	}
	
	public void newOrder(String name, StockOperation operation, int shareNumber, float price) {
		if (engine != null) {
			try {
				engine.addStock(new Stock(name, operation, shareNumber, price));
			} catch (IllegalStockException e) {
				view.showRejectReason(e.getMessage());
			}
		}
	}
	
	public void newOrder(String name, StockOperation operation, int shareNumber) {
		if (engine != null) {
			try {
				engine.addStock(new Stock(name, operation, shareNumber));
			} catch (IllegalStockException e) {
				view.showRejectReason(e.getMessage());
			}
		}
	}

	public void reject(String reasonDetail) {
		view.showRejectReason(reasonDetail);		
	}

	public void refreshStockList() {
		view.refreshStockList();		
	}

	public List<Stock> getStocks() {
		if (engine != null)
			return engine.getStocks();
		else
			return new ArrayList<Stock>();
	}

	public void close() {
		if (engine != null)
			engine.close();
	}
}
